const {
    bestFindClose, findRoleCreepsByRoom, findExtension, findLink, findStore, findTower, findBuilding, findRepair,
    findFreeMainSite, findNuker, findDefaultStore
} = require("./Find");
const {MarketNumber} = require("./Param");
//收集兵运行逻辑
module.exports.harvest = function (creep) {
    let source = Game.getObjectById(creep.memory.source);
    if (source.energy === 0) {
        if (creep.pos.isNearTo(source)) {
            creep.say("💤")
        }
        creep.bestMove(source);
        return;
    }
    if (creep.freeStore() > creep.maxStore() * 0.2) {//如果存在空闲,收集资源
        creep.say("🪓");
        creep.bestHarvest(source)
        return;
    }
    if (source.mineralAmount > 0) {//如果存在矿物,自己运回去
        creep.say("🧊")
        if (creep.room.terminal && creep.room.terminal.freeStore() > 100 * 1000) {
            creep.bestTrans(creep.room.terminal, source.mineralType);
            return;
        }
        creep.bestTrans(creep.room.storage, source.mineralType);
        return;
    }
    let allButler = findRoleCreepsByRoom(creep.room, "管家")
    if (creep.memory.linkId && allButler.length > 0) {//绑定中枢
        let link = Game.getObjectById(creep.memory.linkId)
        if (link.freeStore() > 0) {//存在空闲
            creep.say("🔮")
            if (creep.transfer(link, RESOURCE_ENERGY) === ERR_NOT_IN_RANGE) {//没有like再旁边
                creep.say("🚮")
                creep.drop(RESOURCE_ENERGY);
            }
            return;
        }
        creep.say("💤")
        //存在空闲
        return;
    }
    let linkList = findLink(creep.room);
    if (linkList.length >= 2 && allButler.length>0) {//中枢大于等于2,绑定中枢
        creep.memory.linkId = bestFindClose(creep, linkList).id
        return;
    }
    //初始化房间时判断
    if (allButler.length > 0) {//存在搬运的creep
        creep.say("🚮")
        creep.drop(RESOURCE_ENERGY);
        return;
    }
    let storeList = creep.room.find(FIND_MY_SPAWNS, {filter: spawn => spawn.freeStore() > 0});
    storeList = storeList.concat(findExtension(creep.room, -1));
    if (storeList.length > 0) {
        creep.say("🥫")
        let transStore = creep.findBindClose(storeList);
        creep.bestTrans(transStore)
    }
}

//管家运行逻辑
module.exports.arrange = function (creep) {
    if (creep.memory.closeId) {
    }//隐性bug解决
    let spawn = creep.room.find(FIND_MY_SPAWNS).filter(spawn => !spawn.spawning)[0];
    if (spawn && creep.memory.renew) {
        if (creep.ticksToLive > 1400 || creep.room.energyAvailable < 1500) {
            creep.memory.renew = false;
            return;
        }
        creep.say("🥩")
        if (spawn.renewCreep(creep) === ERR_NOT_IN_RANGE) {
            creep.bestMove(spawn);
        }
        return;
    }

    creep.initFull();
    let mainLink = Game.getObjectById(creep.room.memory.mainLinkId);
    //查看母巢,拓展,炮塔,是否空缺
    let butlerList = findRoleCreepsByRoom(creep.room, "管家");
    let mainList = findFreeMainSite(creep.room).filter(site => {
        for (let butler of butlerList) {
            if (butler.memory.bindId === site.id) {
                return false;
            }
        }
        return true;
    })
    if (creep.memory.isFull) {//背包已满
        //携带了其他能源
        let haveOther = undefined;
        for (let storeKey in creep.store) {
            if (storeKey !== RESOURCE_ENERGY) {
                haveOther = storeKey;
                break;
            }
        }
        let nuker = findNuker(creep.room);
        if (haveOther) {
            creep.say("🧊")
            //查看是否包含go元素
            let goNumber = creep.usedStore(RESOURCE_GHODIUM);
            if (goNumber > 0 && nuker.freeStore(RESOURCE_GHODIUM) > 0) {//身上存在go元素,同时核弹需要填充
                creep.bestTrans(nuker, RESOURCE_GHODIUM);
                return;
            }
            if ((creep.room.terminal && creep.room.terminal.freeStore() > 100 * 10000) || (creep.room.storage && creep.room.storage.freeStore() < 1000)) {
                creep.bestTrans(creep.room.terminal, haveOther);
                return;
            }
            creep.bestTrans(creep.room.storage, haveOther);
            return;
        }
        if (mainList.length > 0) {
            creep.say("👾🍪🏰")
            let transStore = creep.findBindClose(mainList);
            creep.bestTrans(transStore);
            return;
        }
        if (creep.freeStore() > 100) {
            if (creep.room.terminal && nuker && nuker.freeStore(RESOURCE_GHODIUM) > 0 && creep.room.terminal.usedStore(RESOURCE_GHODIUM) > 0) {
                creep.bestWithdraw(creep.room.terminal, RESOURCE_GHODIUM);
                return;
            }

            if (creep.room.storage && nuker && nuker.freeStore(RESOURCE_GHODIUM) > 0 && creep.room.storage.usedStore(RESOURCE_GHODIUM) > 0) {
                creep.bestWithdraw(creep.room.storage, RESOURCE_GHODIUM);
                return;
            }
        }
        //查看是否有市场,同时不存在建造中建筑
        if (creep.room.terminal && creep.room.terminal.freeStore() > 0 && creep.room.storage && creep.room.storage.usedStore() > 900 * 1000) {
            creep.say("🧧")
            creep.bestTrans(creep.room.terminal);
            return;
        }
        //移动到容器中
        let transStore = creep.findBindClose(findDefaultStore(creep.room, -1));
        if (transStore) {
            creep.say("🥫")
            creep.bestTrans(transStore);
            return;
        }
        return;
    }
    //背包未满
    //存在绑定
    if (creep.memory.bindId) {
        let bindSource = Game.getObjectById(creep.memory.bindId);
        if (bindSource === null) {
            creep.memory.bindId = undefined;
            return;
        }
        if (bindSource.resourceType) {//是否为地上资源
            creep.say("📦")
            creep.bestPickup(bindSource);
            return;
        }
        //是否为过期creep
        creep.say("⚰")
        let haveOther;
        for (let storeKey in creep.store) {
            haveOther = storeKey;
            break;
        }
        creep.bestWithdraw(bindSource, haveOther)
        return;
    }
    //如果中枢有能量
    if (mainLink !== null && mainLink.usedStore() > 0) {
        creep.say("🔮")
        creep.bestWithdraw(mainLink)
        return;
    }
    //不存在绑定
    //如果地上有能量
    let droppedResource = bestFindClose(creep, creep.room.find(FIND_DROPPED_RESOURCES, {
        filter: (source) => {
            for (let butler of butlerList) {
                if (butler.memory.bindId === source.id) {
                    return false;
                }
            }
            return source.amount > 100
        }
    }));
    if (droppedResource) {
        creep.memory.bindId = droppedResource.id;
        return;
    }
    //如果地上有过期creep
    let deadCreep = bestFindClose(creep, creep.room.find(FIND_TOMBSTONES, {
        filter: (tombstone) => {
            for (let butler of butlerList) {
                if (butler.memory.bindId === tombstone.id) {
                    return false;
                }
            }
            let haveOther = false;
            for (let storeKey in tombstone.store) {
                if (tombstone.store.getUsedCapacity(storeKey) > 0) {
                    haveOther = true;
                    break;
                }
            }
            return haveOther
        }
    }))
    if (deadCreep) {
        creep.memory.bindId = deadCreep.id;
        return;
    }
    //如果急需能量
    if (mainList.length > 0) {
        let transStore = creep.findBindClose(findStore(creep.room, 1));
        if (transStore) {
            creep.say("🔋")
            creep.bestWithdraw(transStore);
            return;
        }
    }
    //如果terminal能量存在过多,搬到storage
    if (creep.room.terminal && creep.room.terminal.usedStore() > MarketNumber && creep.room.storage && creep.room.storage.freeStore() > 1000) {
        let haveOther;
        for (let storeKey in creep.room.terminal.store) {
            if (storeKey !== RESOURCE_ENERGY) {
                haveOther = storeKey;
                break;
            }
        }
        creep.bestWithdraw(creep.room.terminal, haveOther);
        return;
    }

    //如果等级为4
    if (creep.name.includes("lv4")) {
        if (spawn && creep.ticksToLive < 500 && findRoleCreepsByRoom(creep.room, "管家").length <= 1) {
            creep.memory.renew = true;
        }
    }
    creep.moveToStop();
}

//维修兵运行逻辑
module.exports.repair = function (creep) {
    creep.initFull();
    //背包已满
    if (creep.memory.isFull) {
        let towerList = findTower(creep.room, -1);
        //存在塔容量不足
        if (towerList.length > 0) {
            creep.say("🏰")
            let transStore = creep.findBindClose(towerList);
            creep.bestTrans(transStore);
            return;
        }
        if (!creep.memory.haveTower) {
            let allTower = findTower(creep.room);
            if (allTower.length > 0) {
                creep.memory.haveTower = true;
                return;
            }
            //不存在塔,切有需要维修建筑
            let repairList = findRepair(creep.room);
            if (repairList.length > 0 && findTower(creep.room).length < 1) {//维修建筑
                creep.say("👨‍🔧");
                creep.repairing(repairList)
                return;
            }
        }
        let siteList = creep.room.find(FIND_CONSTRUCTION_SITES);
        if (siteList.length > 0) {
            //没事干,建造
            creep.say("🚧");
            creep.building();
            return;
        }
        if (creep.room.controller.level >= 8) {
            let ticksToDowngrade = creep.room.controller.ticksToDowngrade;
            if (ticksToDowngrade < 100000 || creep.room.storage && creep.room.storage.freeStore() < 100000) {
                creep.memory.mustUp = true;
            } else if (ticksToDowngrade >= 200000) {
                creep.memory.mustUp = false;
            }
        } else {
            creep.memory.mustUp = true;
        }
        if (creep.memory.mustUp) {//没事干,需要升级
            creep.say("✨")
            creep.bestUpController(creep.room.controller);
            return;
        }
        return;
    }
    let containersWithResources = creep.room.find(FIND_STRUCTURES, {filter: structure => (structure.structureType === STRUCTURE_CONTAINER || structure.structureType === STRUCTURE_STORAGE)});
    let upLink = Game.getObjectById(creep.room.memory.upLinkId);
    if (upLink && creep.pos.inRangeTo(upLink, 3)) {
        if (findFreeMainSite(creep.room).length > 0 && containersWithResources.length < 2) {
            creep.say("💤")
            return;
        }
        if (upLink.usedStore() > 0) {
            creep.bestWithdraw(upLink);
            return;
        }
    }
    creep.bestGetSource();
}
//建造兵运行逻辑
module.exports.build = function (creep) {
    creep.initFull();
    //背包已满
    if (creep.memory.isFull) {
        let siteList = creep.room.find(FIND_CONSTRUCTION_SITES);
        if (siteList.length > 0) {//建造
            creep.say("🚧");
            creep.building();
            return;
        }
        //没事干,升级
        creep.say("✨")
        creep.bestUpController(creep.room.controller);
        return
    }
    //获取能量
    creep.bestGetSource();
}

//升级兵运行逻辑
module.exports.up = function (creep) {
    creep.initFull();
    //背包已满
    if (creep.memory.isFull) {
        if (!creep.room.controller.sign || creep.room.controller.sign.username !== "BALCKJUNWIN") {
            creep.signController(creep.room.controller, "");
            if (creep.signController(creep.room.controller, "Peaceful development✨!") === ERR_NOT_IN_RANGE) {
                creep.bestMove(creep.room.controller);
            }
        }
        creep.say("✨")
        creep.bestUpController(creep.room.controller);
        return;
    }
    //背包未满
    let containersWithResources = creep.room.find(FIND_STRUCTURES, {filter: structure => (structure.structureType === STRUCTURE_CONTAINER || structure.structureType === STRUCTURE_STORAGE)});
    if (findFreeMainSite(creep.room).length > 0 && containersWithResources.length < 2) {
        creep.say("💤")
        return;
    }
    let upLink = Game.getObjectById(creep.room.memory.upLinkId);
    if (upLink && upLink.usedStore() > 0) {
        creep.bestWithdraw(upLink);
        return;
    }

    creep.bestGetSource();
}

//防御兵运行逻辑
module.exports.defense = function (creep) {
    let hostileList = creep.room.find(FIND_HOSTILE_CREEPS);
    if (hostileList.length > 0) {
        creep.say("💢");
        creep.bestAttack(bestFindClose(creep, hostileList))
    }
}

function wellDead(creep, tick) {
    if (tick < 20) {
        creep.say("🙉")
        if (creep.usedStore() > 10) {
            let transStore = creep.findBindClose(findStore(creep.room, -1));
            if (transStore) {
                creep.bestTrans(transStore);
                return;
            }
            creep.suicide();
            return;
        }
        creep.suicide();
    }
}